import React, { useState } from 'react';
import { Table, Button, Input, DatePicker, Select, Form } from 'antd';
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';
import { useEffect } from 'react';
import { api, queryList } from '../api/api';
import Url from '../api/url';
import { message } from 'antd';
import { Modal } from 'antd';

function SaleFlowPage() {
  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  const [pageSize, setPageSize] = useState(20); 
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const user = JSON.parse(localStorage.getItem('user'))
  const isAdmin = user?.USERID === 'admin';

  const columns = [
  // { title: 'PK', dataIndex: 'PK', key: 'PK' },
  { title: '单据编号', dataIndex: 'BILLID', key: 'BILLID', width: 120 },
  { title: '销售日期', dataIndex: 'SALE_DATE', key: 'SALE_DATE',width: 110,render:(text) => text ? dayjs(text).format('YYYY-MM-DD') : '-'  },
  { title: '销售方代码', dataIndex: 'SELLER_CODE', key: 'SELLER_CODE', width: 120 },
  { title: '销售方名称', dataIndex: 'SELLER_NAME', key: 'SELLER_NAME', width: 200 },
  { title: '采购方代码', dataIndex: 'BUYER_CODE', key: 'BUYER_CODE', width: 120 },
  { title: '收货单位名称', dataIndex: 'BUYER_NAME', key: 'BUYER_NAME', width: 280 },
  { title: '生产厂家', dataIndex: 'MANUFACTURER', key: 'MANUFACTURER', width: 150 },
  { title: '产品编码', dataIndex: 'PRODUCT_CODE', key: 'PRODUCT_CODE', width: 120 },
  { title: '商品名称', dataIndex: 'PRODUCT_NAME', key: 'PRODUCT_NAME', width: 150 },
  { title: '商品规格', dataIndex: 'PRODUCT_SPEC', key: 'PRODUCT_SPEC', width: 150 },
  { title: '产品剂型', dataIndex: 'PRODUCT_FORM', key: 'PRODUCT_FORM', width: 100 },
  { title: '产品通用名', dataIndex: 'PRODUCT_GENERIC_NAME', key: 'PRODUCT_GENERIC_NAME', width: 150 },
  { title: '批号', dataIndex: 'BATCH_NO', key: 'BATCH_NO', width: 100 },
  { title: '有效期至', dataIndex: 'EXPIRY_DATE', key: 'EXPIRY_DATE',width: 110,
    render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '-' },
  { title: '数量', dataIndex: 'QUANTITY', key: 'QUANTITY', width: 80 },
  { title: '单位', dataIndex: 'UNIT', key: 'UNIT', width: 80 },
  { title: '含税单价', dataIndex: 'TAXED_PRICE', key: 'TAXED_PRICE', width: 100 },
  { title: '含税金额', dataIndex: 'TAXED_AMOUNT', key: 'TAXED_AMOUNT', width: 100 },
  { title: '收货地址', dataIndex: 'DELIVERY_ADDRESS', key: 'DELIVERY_ADDRESS', width: 200 },
  { title: '是否退货', dataIndex: 'IS_RETURN', key: 'IS_RETURN', width: 100 },
  { title: '创建日期', dataIndex: 'CREATE_DATE', key: 'CREATE_DATE',width: 110,
    render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '-' }
];

  // 查询功能mock
  const handleSearch = async () => {
    // 这里可根据form.getFieldsValue()过滤data
  
    const fields = form.getFieldsValue()
    fields.startDate =  fields.startDate ? fields.startDate.format('YYYY-MM-DD') : null
    fields.endDate = fields.endDate ? fields.endDate.format('YYYY-MM-DD') : null
    fields.userId = user.USERID
    const dataList = await queryList({url:Url.getSaleRecord,params:fields})
    setData(dataList)
  };

  const pageLoad = async () =>{
    const fields = form.getFieldsValue()
    fields.startDate =  fields.startDate ? fields.startDate.format('YYYY-MM-DD') : null
    fields.endDate = fields.endDate ? fields.endDate.format('YYYY-MM-DD') : null
    fields.userId = user.USERID
    const dataList = await queryList({url:Url.getSaleRecord,params:fields})
    setData(dataList)
  }

  const deleteRecord = async () => {

    if (selectedRowKeys.length === 0) return;
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的${selectedRowKeys.length}条记录吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await api({url:Url.deleteRecord,data:{table:'tb_flow_sales_records',pkList:selectedRowKeys}})
            setData(data.filter(u => !selectedRowKeys.includes(u.PK)));
            setSelectedRowKeys([]);
            message.success(res.msg);
      },
    });
  }

  useEffect(()=>{
    pageLoad()
  },[])

  // 导出Excel功能（字段中文）
  const handleExport = () => {
    // 字段映射
    const exportData = data.map(row => ({
        '单据编号': row.BILLID,
        '销售日期': row.SALE_DATE,
        '销售方代码': row.SELLER_CODE,
        '销售方名称': row.SELLER_NAME,
        '采购方代码': row.BUYER_CODE,
        '收货单位名称': row.BUYER_NAME,
        '生产厂家': row.MANUFACTURER,
        '产品编码': row.PRODUCT_CODE,
        '商品名称': row.PRODUCT_NAME,
        '商品规格': row.PRODUCT_SPEC,
        '产品剂型': row.PRODUCT_FORM,
        '产品通用名': row.PRODUCT_GENERIC_NAME,
        '批号': row.BATCH_NO,
        '有效期至': row.EXPIRY_DATE,
        '数量': row.QUANTITY,
        '单位': row.UNIT,
        '含税单价': row.TAXED_PRICE,
        '含税金额': row.TAXED_AMOUNT,
        '收货地址': row.DELIVERY_ADDRESS,
        '是否退货': row.IS_RETURN,
        '创建日期': row.CREATE_DATE
    }));
    const ws = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '销售流向');
    XLSX.writeFile(wb, '销售流向.xlsx');
  };

  return (
    <div style={{ padding: 16, background: '#f5f6fa' }}>
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 16, background: '#fff', padding: 16, borderRadius: 8, flexWrap: 'wrap' }}
        clearOnDestroy
        initialValues={{
          startDate: dayjs().startOf('month'),  // 设置为当月第一天
          endDate: dayjs(),  // 设置为当前日期
          manufacturer:'',
          productCode:'',
          productName:'',
        }}
      >
        <Form.Item label="生产厂家" name="manufacturer">
          <Input style={{ width: 160 }} />
        </Form.Item>
        <Form.Item label="商品编码" name="productCode">
          <Input style={{ width: 160 }} />
        </Form.Item>
        <Form.Item label="商品名称" name="productName">
          <Input style={{ width: 160 }} />
        </Form.Item>
        <Form.Item label="开始日期" name="startDate">
          <DatePicker style={{ width: 140 }}  />
        </Form.Item>
        <Form.Item label="截至日期" name="endDate">
          <DatePicker style={{ width: 140 }}   />
        </Form.Item>
        
        <Form.Item>
          <Button type="primary" onClick={handleSearch}>检索</Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleExport}>导出</Button>
        </Form.Item>

        <Form.Item>
          {isAdmin && (
            <Button danger onClick={deleteRecord} >
              删除
            </Button>
          )}
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        dataSource={data}
        bordered
        pagination={{ 
          showSizeChanger:true,
          pageSizeOptions: ['10', '20', '50', '100'],
          pageSize: pageSize, showTotal: total => `共${total}条` ,
          onShowSizeChange: (current, size) => {
            setPageSize(size);
          }
        }}
        style={{ background: '#fff', borderRadius: 8}}
        scroll={{ x: '100%', y: 'calc(100vh - 260px)' }}
        rowKey={'PK'}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
      />
    </div>
  );
}

export default SaleFlowPage;